<template>
  <div class="report-define-wrap">
    <div class="report-preview">
      <h5>统计预览 <span style="font-size: 13px; color: red">(保存后才能预览最新数据)</span></h5>
      <div class="report-support-types">
        <div
          class="item-type"
          @click="handleSelectChartType('table')"
          :class="{ active: currentChart === 'table' }"
        >
          <JIcon :icon="DFT_ICONS.chartTable" />
        </div>

        <div
          class="item-type"
          @click="handleSelectChartType('bar')"
          :class="{
            active: currentChart === 'bar',
            disabled: !$reportUtils.canChartBar(form)
          }"
        >
          <JIcon :icon="DFT_ICONS.chartBar" />
        </div>

        <div
          class="item-type"
          @click="handleSelectChartType('line')"
          :class="{
            active: currentChart === 'line',
            disabled: !$reportUtils.canChartLine(form)
          }"
        >
          <JIcon :icon="DFT_ICONS.chartLine" />
        </div>

        <div
          class="item-type"
          @click="handleSelectChartType('pie')"
          :class="{
            active: currentChart === 'pie',
            disabled: !$reportUtils.canChartPie(form)
          }"
        >
          <JIcon :icon="DFT_ICONS.chartPie" />
        </div>

        <div
          class="item-type"
          @click="handleSelectChartType('card')"
          :class="{
            active: currentChart === 'card',
            disabled: !$reportUtils.canChartCard(form)
          }"
        >
          <JIcon :icon="DFT_ICONS.chartCard" />
        </div>
      </div>

      <div class="report-view" v-if="targetForm && targetForm.form_id">
        <jzl-chart-table v-if="currentChart === 'table'" :item="tableOption" />

        <div v-else-if="currentChart === 'pie'" class="v-chart-area">
          <v-chart
            :option="pieChartOption"
            v-if="currentChart === 'pie'"
            key="pie"
            :init-options="initOptions"
            @click="handleChartClick"
            autoresize
          />
        </div>

        <div v-else-if="isChartType" class="v-chart-area">
          <v-chart
            :option="chartOption"
            @click="handleChartClick"
            key="chart"
            :init-options="initOptions"
            autoresize
          />
        </div>

        <jzl-chart-card
          v-if="currentChart === 'card' && cardOption"
          :item="cardOption"
          style="margin-top: 80px"
        />

        <el-dialog
          v-model="detailShow"
          :title="detailTitle"
          custom-class="form-dialog-fullscreen"
          :close-on-click-modal="false"
          :append-to-body="true"
        >
          <datas-chart
            v-if="detailShow"
            :chart-data-id="chartDataId"
            :chart-item-id="chartItemId"
            style="padding: 10px"
          />
        </el-dialog>
      </div>
    </div>

    <div class="report-define">
      <el-radio-group v-model="form.type" size="mini" style="margin: 0 auto 10px" :disabled="isUpdate">
        <el-radio-button :label="1">定义报表</el-radio-button>
        <el-radio-button :label="3">低码注册</el-radio-button>
      </el-radio-group>

      <el-form ref="formRef" :model="form" :rules="formRules" size="mini" label-width="70px" class="report-define-form">
        <el-form-item label="报表名" prop="title">
          <el-input v-model="form.title" placeholder="名称，如：产品年度销售统计" :disabled="isView" />
        </el-form-item>

        <template v-if="form.type === 3">
          <el-form-item label="报表编码" prop="reportdef_code">
            <el-input v-model="form.reportdef_code" placeholder="报表编码" :disabled="isView || isUpdate" />
          </el-form-item>

          <el-form-item label="图表类型">
            <el-checkbox-group v-model="form.scharts">
              <el-checkbox-button label="table">
                <i class="fa fa-table" v-tippy="{ arrow: true }" content="表格"></i>
              </el-checkbox-button>
              <el-checkbox-button label="bar">
                <i class="fa fa-chart-bar" v-tippy="{ arrow: true }" content="柱状图"></i>
              </el-checkbox-button>
              <el-checkbox-button label="line">
                <i class="fa fa-chart-line" v-tippy="{ arrow: true }" content="折线图"></i>
              </el-checkbox-button>
              <el-checkbox-button label="pie">
                <i class="fa fa-chart-pie" v-tippy="{ arrow: true }" content="饼图"></i>
              </el-checkbox-button>
              <el-checkbox-button label="card">
                <i class="fa fa-credit-card" v-tippy="{ arrow: true }" content="数字卡"></i>
              </el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="低码开发">
            <div class="report-lowcode-tag">
              <i class="fa fa-node-js"></i>
              <span v-if="!isUpdate">注册后才能设置低码</span>
              <span v-else-if="form.func_id" @click="handleShowCreateOrEditFunc">低码已设置</span>
              <span v-else @click="handleShowCreateOrEditFunc">低码未设置</span>
            </div>
          </el-form-item>
        </template>

        <template v-else>
          <el-form-item label="数据源">
            <template v-if="!isView">
              <el-tag
                v-if="targetForm?.form_id"
                size="large"
                style="margin-right: 10px">
                {{ targetForm.form_name }}
                <JIcon
                  :icon="DFT_ICONS.braceLeft"
                />{{ viewLabel(targetView) }}
                <JIcon
                  :icon="DFT_ICONS.braceRight"
                />
              </el-tag>
              <el-button
                type="primary"
                @click="handleShowFormSelectWin"
              >选择表单</el-button>
            </template>
            <template v-else-if="targetForm">
              <el-tag size="medium">
                {{ targetForm.form_name }}
                <JIcon
                  :icon="DFT_ICONS.braceLeft"
                />{{ viewLabel(targetView) }}
                <JIcon
                  :icon="DFT_ICONS.braceRight"
                />
              </el-tag>
            </template>
          </el-form-item>

          <el-form-item label="行维度">
            <table class="table table-bordered m-table-border" v-if="form.xaxis.length">
              <tbody>
              <tr v-for="(dr, idx) in form.xaxis" :key="idx">
                <td style="width: 160px">
                  <el-select v-model="dr.propType" @change="handlePropTypeChange(dr)" placeholder="统计类型" size="mini">
                    <el-option v-for="it in FORM_TYPES" :key="it.value" :value="it.value" :label="it.label" />
                  </el-select>
                </td>
                <td>
                  <el-select
                    v-model="dr.prop"
                    @change="handlePropChange(dr)"
                    filterable
                    placeholder="表单项"
                    size="mini"
                  >
                    <template
                      v-for="it in (formTypeMap[dr.propType]?.items || [])"
                      :key="it.name"
                    >
                      <el-option
                        :value="it.name"
                        :label="it.label"
                        v-if="checkItemSupport(it, 'xaxis')"
                      />
                    </template>
                  </el-select>
                </td>
                <td style="width: 30px">
                  <i class="el-icon-error remove-btn" @click="handleRemoveRow(idx, 'xaxis')"></i>
                </td>
              </tr>
              </tbody>
            </table>
            <el-button
              type="primary"
              size="small"
              plain
              :disabled="!targetForm || !targetForm.form_id"
              @click="handleAddRow('xaxis')"
            >
              <template #icon>
                <JIcon :icon="DFT_ICONS.add" />
              </template>
              添加维度
            </el-button>
          </el-form-item>

          <el-form-item label="列维度">
            <table class="table table-bordered m-table-border" v-if="form.yaxis.length">
              <tbody>
              <tr v-for="(dr, idx) in form.yaxis" :key="idx">
                <td style="width: 160px">
                  <el-select v-model="dr.propType" @change="handlePropTypeChange(dr)" placeholder="统计类型" size="mini">
                    <el-option v-for="it in FORM_TYPES" :key="it.value" :value="it.value" :label="it.label" />
                  </el-select>
                </td>
                <td>
                  <el-select
                    v-model="dr.prop"
                    @change="handlePropChange(dr)"
                    filterable
                    placeholder="表单项"
                    size="mini"
                  >
                    <el-option
                      v-for="it in (formTypeMap[dr.propType]?.items || [])"
                      :key="it.name"
                      :value="it.name"
                      :label="it.label"
                      v-if="checkItemSupport(it, 'yaxis')"
                    />
                  </el-select>
                </td>
                <td style="width: 30px">
                  <i class="el-icon-error remove-btn" @click="handleRemoveRow(idx, 'yaxis')"></i>
                </td>
              </tr>
              </tbody>
            </table>
            <el-button
              type="primary"
              size="small"
              plain
              :disabled="!targetForm || !targetForm.form_id"
              @click="handleAddRow('yaxis')"
            >
              <template #icon>
                <JIcon :icon="DFT_ICONS.add" />
              </template>
              添加维度
            </el-button>
          </el-form-item>
          <el-form-item label="指标">
            <table class="table table-bordered m-table-border" v-if="form.zaxis.length">
              <tbody>
              <tr v-for="(dr, idx) in form.zaxis" :key="idx">
                <td>
                  <el-select
                    v-model="dr.prop"
                    @change="handlePropChange(dr)"
                    filterable
                    placeholder="表单项"
                    size="mini"
                  >
                    <el-option value="_data_id" label="数据"></el-option>
                    <el-option
                      v-for="it in targetForm.items"
                      :key="it.name"
                      :value="it.name"
                      :label="it.label"
                      v-if="checkItemSupport(it, 'zaxis')"
                    />
                  </el-select>
                </td>
                <td style="text-align: center">
                  <el-select
                    v-model="dr.stat_mode"
                    @change="handlePropChange(dr)"
                    filterable
                    placeholder="汇总方式"
                    size="mini"
                  >
                    <el-option v-if="dr.prop === '_data_id'" value="COUNT" label="计数"></el-option>
                    <template
                      v-for="sm in STAT_MODES"
                      :key="sm">
                      <el-option
                        v-if="checkItemStatModeSupport(sm, dr)"
                        :value="sm.value"
                        :label="sm.name"
                      />
                    </template>
                  </el-select>
                </td>
                <td><el-input placeholder="显示名" v-model="dr.label" /></td>
                <td style="width: 30px">
                  <JIcon
                    :icon="DFT_ICONS.error"
                    class="remove-btn"
                    @click="handleRemoveRow(idx, 'zaxis')"
                  />
                </td>
              </tr>
              </tbody>
            </table>
            <el-button
              type="primary"
              size="small"
              plain
              :disabled="!targetForm || !targetForm.form_id"
              @click="handleAddRow('zaxis')"
            >
              <template #icon>
                <JIcon :icon="DFT_ICONS.add" />
              </template>
              添加指标
            </el-button>
            <span style="font-size: 12px; color: #000; margin-left: 10px"
            >指标、行维度、列维度字段不能互相重复！</span
            >
          </el-form-item>

          <el-form-item label="数据过滤">
            <Rules
              v-if="targetForm?.form_id"
              v-model="form.datarules"
              type="data"
              :input-form="targetForm"
              :force-enable="true"
              style="width: 100%"
            />
          </el-form-item>
        </template>

        <el-form-item label="更新间隔">
          <div class="flex w-full align-center">
            <el-slider v-model="form.cron" class="flex-1" />
            <span v-text="form.cron" style="margin: 0 10px; width: 50px; text-align: center"></span>
            <el-select v-model="form.cron_type" style="width: 90px">
              <el-option label="分钟" :value="1" />
              <el-option label="小时" :value="2" />
              <el-option label="天" :value="3" />
            </el-select>
          </div>
          <p style="color: #999; font-size: 12px; margin: 3px 0">
            在间隔时间内，读取最新计算的缓存数据，不重复计算，除非点击强制更新。
          </p>
        </el-form-item>
      </el-form>

      <div class="actions">
        <el-button size="large" type="primary" @click="handleSubmit">保存</el-button>
        <el-button size="large" @click="handleCancel">取消</el-button>
      </div>
    </div>

    <el-drawer
      :title="funcFormWinName"
      v-model="funcFormWinShow"
      :append-to-body="true"
      :with-header="false"
      size="96%"
      :wrapperClosable="false"
      direction="rtl"
      class="wf-node-prop-drawer"
    >
      <div class="func-form-body">
        <lownode-func
          v-model="funcForm"
          :app-id="appId"
          :type="4"
          code-type="serverReport"
          :has-input="false"
          :has-output="false"
        >
          <div class="func-form-actions" slot="header-tools">
            <el-button @click="funcFormWinShow = false" size="small" style="width: 80px">取消</el-button>
            <el-button type="primary" @click="handleFuncSave" size="small" style="width: 80px">保存</el-button>
          </div>
        </lownode-func>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import _ from 'lodash'
import {$reportUtils} from "@jzl/utils";
import {api} from "@jzl/api";
import {$WinForms} from "@jzl/comps";
import {DFT_ICONS} from "@jzl/icons";

const emit = defineEmits(['close'])
// props
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  modId: null,
  inputFormId: {
    type: [String, Number]
  }
})

// 常量
const dft = {
  type: 1,
  reportdef_id: null,
  reportdef_code: null,
  title: '',
  remark: '',
  form_id: '',
  view_id: -1,
  xaxis: [],
  yaxis: [],
  zaxis: [],
  xyaxis_size: 0,
  zaxis_size: 0,
  datarules: {},
  search_fields: [],
  cron_type: 1,
  cron: 5,
  scharts: [],
  func_id: null
}

const STAT_ITEMTYPE_MODES = {
  radio: ['COUNT'],
  checkbox: ['COUNT'],
  mb: ['COUNT'],
  number: ['COUNT', 'SUM', 'AVG', 'MAX', 'MIN'],
  date: ['COUNT'],
  string: ['COUNT'],
  formrel: ['COUNT']
}

const OPTIONS = {
  bar: {
    legend: {},
    tooltip: {},
    xAxis: { type: 'category' },
    yAxis: {}
  },
  line: {
    label: { show: true },
    legend: {},
    tooltip: {},
    xAxis: { type: 'category' },
    yAxis: {}
  },
  pie: {
    label: { show: true },
    legend: { orient: 'vertical', left: 'left' },
    tooltip: {}
  }
}

const viewCfg = {
  box_style: {
    header: {
      _common_style: { display: 'none' }
    }
  },
  data_type: 'dync',
  data_dync: {}
}

// 响应式状态
const form = reactive(_.cloneDeep(dft))
const formRules = reactive({
  title: [{ required: true, message: '请输入报表名称', trigger: 'blur' }]
})
const FORM_TYPES = reactive([
  { label: '当前表单', value: 'targetForm' },
  { label: '人员属性', value: 'admin' }
])
const STAT_MODES = reactive([
  { name: '计数', value: 'COUNT' },
  { name: '求和', value: 'SUM' },
  { name: '平均值', value: 'AVG' },
  { name: '最大值', value: 'MAX' },
  { name: '最小值', value: 'MIN' }
])
const formTypeMap = reactive({ targetForm: null, admin: null })
const loading = ref(false)
const isView = ref(false)
const targetForm = ref(null)
const targetView = ref(null)
const adminForm = ref(null)
const currentChart = ref('card')
const initOptions = reactive({ renderer: 'svg' })
const dataset = reactive({ dimensions: [], source: [] })
const detailTitle = ref('')
const detailShow = ref(false)
const chartDataId = ref(null)
const chartItemId = ref(null)
const origChartData = ref(null)
const realChartOption = ref(null)
const appId = ref(null)
const funcType = ref(4)
const funcForm = ref(null)
const funcFormWinShow = ref(false)
const funcFormWinName = ref('')
const formRef = ref(null)

// 计算属性
const isChartType = computed(() => ['line', 'pie', 'bar'].includes(currentChart.value))
const chartOption = computed(() => {
  const type = ['line', 'pie', 'bar'].includes(currentChart.value) ? currentChart.value : 'line'
  return getChartOption(type)
})
const pieChartOption = computed(() => getChartOption('pie'))
const cardOption = computed(() =>
  _.merge({}, viewCfg, {
    component: 'jzlChartCard',
    data_dync: {
      reportdef_code: isUpdate.value ? _.get(form, 'reportdef_code') : null
    }
  })
)
const tableOption = computed(() =>
  _.merge({}, viewCfg, {
    component: 'jzlChartTable',
    data_dync: {
      reportdef_code: isUpdate.value ? _.get(form, 'reportdef_code') : null
    }
  })
)
const isUpdate = computed(() => _.get(form, 'reportdef_id') > 0)

// 方法
function viewLabel(view) {
  return view?.view_name || '默认'
}

async function init() {
  dataset.dimensions = []
  dataset.source = []
  targetForm.value = null
  targetView.value = null

  if (props.modId) {
    const res = await api.report.getReportDef(props.modId)
    Object.assign(form, res)
  } else {
    const newForm = _.cloneDeep(dft)
    if (props.inputFormId) newForm.form_id = props.inputFormId
    newForm.reportdef_code = $utils.getNanoid()
    Object.assign(form, newForm)
  }

  await loadForm()
  await loadAdminForm()
  await initDataset()
}

async function loadForm() {
  if (!form.form_id) return
  const res = await api.form.getFormById(form.form_id, form.view_id)
  if (res && res.form_id) {
    targetForm.value = res
    targetView.value = res.view
  }

  // 处理关联表单项
  const formCode = _.get(res, 'form_code')
  const items = _.get(res, 'items', [])
  const formName = _.get(res, 'form_name')

  if (formCode !== '_ADMIN') {
    _.each(items, it => {
      if (it.type !== 'formrel' || it.form_item_code === '_ADMIN') return
      const relForm = _.get(it, 'form')
      const relFormCode = _.get(relForm, 'form_code')
      const key = `${formCode}@${it.name}`
      const formLabel = `${formName}.${it.label}`

      if (relFormCode) {
        relForm.form_key = key
        relForm.form_label = formLabel
        if (!_.find(FORM_TYPES, { value: key })) {
          FORM_TYPES.push({ label: formLabel, value: key })
        }
        formTypeMap[key] = relForm
      }
    })
  }

  formTypeMap.targetForm = res
}

async function loadAdminForm() {
  if (adminForm.value) return adminForm.value;
  const res = await api.form.getFormByCode('_ADMIN')

  let items = _.get(res, 'items', []);
  let fixedItems = [
    { name: 'dept_id', label: '部门', type: 'dept' },
    /* { name: 'dept_post_id', label: '职务', type: 'deptpost' }, */
    { name: 'loginname', label: '登录名', type: 'input' },
    { name: 'mobile', label: '手机号', type: 'mobile' },
    { name: 'nickname', label: '姓名', type: 'input' },
    { name: 'id', label: '人员ID', type: 'number' },
    /*{ name: 'num', label: 'number测试', type: 'number' }*/
  ];

  for(let i = 0; i < fixedItems.length; i++) {
    let it = fixedItems[i];
    let name = it.name;
    let idx = _.findIndex(items, { name: name });

    if(idx < 0) {
      items.unshift(it)
    }
  }

  adminForm.value = res
  formTypeMap.admin = res
}

const initItemOptions = async () => {
  let items = _.get(targetForm.value, 'items', []);

  for(let i = 0; i < items.length; i++) {
    await initOption(items[ i ]);
  }
}

const initOption = async (item) => {
  if(!item) return;
  if(item.type === 'mb') {}
}

async function initDataset() {
  if (!form.reportdef_id) return
  const data = await api.report.getReportDataByDefine(form.reportdef_id)
  const ds = data?.datalist;

  origChartData.value = data
  if (ds) {
    Object.assign(dataset, ds)
  }
}

function formatDataset(datasetOrig) {
  const dataset = _.cloneDeep(datasetOrig)
  const origDimensions = _.cloneDeep(_.get(datasetOrig, 'dimensions', []))
  const origSource = _.cloneDeep(_.get(datasetOrig, 'source', []))

  let dimensions = origDimensions
  let source = origSource

  // 柱状 & 折线图表支持 xzzzz...(多指标，无需转换) | xxz | xyz | yyz（一个指标，2个维度，需要转换）
  // 转化规则：将 [{ x:'x', y: 'y1', z: 1 }, { x: 'x', y: 'y2', z: 2 }] => [{ x: 'x', y1: 1, y2: 2 }]
  // 转化说明：将 xyz 中间一位，转化为 series, y取值有多个，则有多个 dimensions，意思就是将y转换成指标
  let isNeedTransform = false;

  if (origDimensions?.length === 3) {
    const xyAxis = _.filter(origDimensions, d => ['x', 'y'].includes(d.axisType))
    isNeedTransform = xyAxis.length === 2;
  }

  if(isNeedTransform) {
    const xCol = origDimensions.shift()
    const yCol = origDimensions.shift()
    const zCol = origDimensions.shift()
    const xName = _.get(xCol, 'name')
    const yName = _.get(yCol, 'name')
    const zName = _.get(zCol, 'name')

    dimensions = [xCol]
    const yVals = _.uniq(_.map(origSource, yName))

    _.each(yVals, val => {
      dimensions.push({ name: `${yName}-${val}`, axisType: 'y', displayName: val })
    })

    source = []

    _.each(_.uniq(_.map(origSource, xName)), xVal => {
      const sou = { [xName]: xVal }
      _.each(yVals, yVal => {
        const colKey = `${yName}-${yVal}`
        const item = _.find(origSource, { [xName]: xVal, [yName]: yVal })
        sou[colKey] = _.get(item, zName)
        sou[`${colKey}_id`] = _.get(item, '_id')
      })
      source.push(sou)
    })
  }

  dataset.dimensions = dimensions
  dataset.source = source
  return dataset
}

function getChartOption(type) {
  const iDataset = formatDataset(dataset)
  const dimensions = _.get(iDataset, 'dimensions', [])
  const dimensionNum = dimensions.length > 1 ? dimensions.length - 1 : 1

  const option = _.cloneDeep(OPTIONS[type])
  const series = Array.from({ length: dimensionNum }, () => ({
    type,
    barGap: 0,
    label: { rotate: 45 }
  }))

  option.dataset = iDataset
  option.series = series
  realChartOption.value = option
  return option
}

function close(flag) {
  emit('close', flag)
}

function handleShowFormSelectWin() {
  $WinForms({
    type: 'view',
    onConfirm: info => {
      const iForm = _.get(info, 'form')
      const iView = _.get(info, 'view')
      if (!iForm || !iForm.form_id) return
      form.form_id = iForm.form_id
      form.view_id = _.get(iView, 'form_view_id', -1)
    }
  })
}

function checkItemSupport(item, type) {
  if (type === 'xaxis' || type === 'yaxis') {
    return ['radio', 'checkbox', 'mb', 'number', 'date', 'dept', 'input', 'formrel'].includes(item?.type)
  } else if (type === 'zaxis') {
    return ['radio', 'checkbox', 'mb', 'number', 'date', 'input', 'formrel'].includes(item?.type)
  }
  return false
}

function checkItemStatModeSupport(statMode, axis) {

  console.log(statMode, axis)
  const name = _.get(axis, 'prop')
  const item = _.find(targetForm.value?.items, { name }) ?? null
  const type = _.get(item, 'type')
  return _.includes(STAT_ITEMTYPE_MODES[type], statMode.value)
}

function handleAddRow(type) {
  form[type].push({ propType: 'targetForm', prop: '' })
}

function handleRemoveRow(idx, type) {
  form[type].splice(idx, 1)
}

async function handleSubmit() {
  const valid = await formRef.value.validate().catch(() => false)
  if (!valid) return

  let ret = null
  const kv = _.cloneDeep(form)
  if (props.modId) {
    ret = await api.report.updateReportDef(kv)
  } else {
    ret = await api.report.createReportDef(kv)
  }

  if (ret?.reportdef_id) {
    props.modId = ret.reportdef_id
    $jui.toast('操作成功！')
    $jui.notify({
      title: '提示',
      message: '操作成功！',
      type: 'success'
    });
    const refreshData = await api.report.createReportData(ret.reportdef_id)
    if (refreshData) await initDataset()
  } else {
    $jui.notify({
      title: '提示',
      message: '操作失败，请稍后再试！',
      type: 'error'
    });
  }
}

function handleCancel() {
  close(false)
}

function handleSelectChartType(type) {
  if (type === 'pie') currentChart.value = ''
  setTimeout(() => {
    currentChart.value = type
  }, 0)
}

function handlePropTypeChange(item) {
  item.prop = ''
}

function handlePropChange() {}

function handleChartClick(chartItem) {
  const data = _.get(chartItem, 'data')
  const iChartDataId = _.get(origChartData.value, 'reportdata_id')
  const iChartItemId = (() => {
    const componentType = _.get(chartItem, 'componentType')
    const seriesIndex = _.get(chartItem, 'seriesIndex')
    if (componentType === 'series') {
      const dim = _.get(realChartOption.value, `dataset.dimensions[${seriesIndex + 1}]`)
      const realProp = dim ? `${dim.name}_id` : ''
      return _.get(data, realProp) ?? _.get(data, '_id')
    }
    return _.get(data, '_id')
  })()

  if (chartItemId == null) return

  chartDataId.value = iChartDataId
  chartItemId.value = iChartItemId

  const percent = _.get(chartItem, 'percent')
  const name = _.get(chartItem, 'name')
  const seriesName = _.get(chartItem, 'seriesName')
  detailTitle.value = `${seriesName || ''}为${name || ''}${percent ? `占比${percent}%` : ''}`
  detailShow.value = true
}

function handleShowCreateOrEditFunc() {
  const reportdef_id = _.get(form, 'reportdef_id')
  if (!reportdef_id) return
  funcForm.value = _.cloneDeep(form.func) || null
  funcFormWinShow.value = true
}

async function handleFuncSave() {
  const reportdef_id = _.get(form, 'reportdef_id')
  const f = _.cloneDeep(funcForm.value)
  if (!f || !reportdef_id) return

  loading.value = true
  const ret = await api.report.reportFuncCreate(reportdef_id, f)
  if (ret) {
    funcFormWinShow.value = false
    await init()
  }
  loading.value = false
}

// Watchers
watch(
  () => props.show,
  val => {
    if (val) init()
  }
)
watch(
  () => props.modId,
  val => {
    init()
  }
)
watch(
  () => form.form_id,
  () => {
    loadForm()
  }
)
watch(
  () => targetForm.value,
  () => {
    initItemOptions()
  }
)
watch(
  () => form.xaxis,
  () => {
    form.xyaxis_size = (form.xaxis?.length || 0) + (form.yaxis?.length || 0)
  },
  { deep: true }
)
watch(
  () => form.yaxis,
  () => {
    form.xyaxis_size = (form.xaxis?.length || 0) + (form.yaxis?.length || 0)
  },
  { deep: true }
)
watch(
  () => form.zaxis,
  () => {
    form.zaxis_size = form.zaxis?.length || 0
  },
  { deep: true }
)

onMounted(() => {
  init()
})
</script>

<style lang="scss">
.report-define {
  padding-top: 5px;

  .el-form-item__label {
    padding-bottom: 0px;
    color: #999;
    font-size: 13px;
  }
}

</style>
<style lang="scss" scoped>
.report-define-wrap {
  display: flex;
  height: 100%;
  background: #FFF;

  .report-define {
    width: 600px;
    padding-right: 10px;
    padding-top: 10px;
    height: 100%;
    overflow: auto;
    display: flex;
    flex-flow: column;

    h5 {
      font-size: 13px;
      font-weight: bold;
      margin: 0px;
    }

    .report-define-form {
      flex: 1;
      height: 100%;
      overflow-y: auto;

      background: #FCFCFC;
      padding: 15px 10px;
      border-radius: 5px;
      border: 1px solid #EEE;
    }

    .actions {
      text-align: center;
      padding: 10px;
    }
  }

  .report-preview {
    flex: 1;
    margin: 20px 10px 0px 10px;
    display: flex;
    flex-flow: column;
    padding-bottom: 30px;

    h5 {
      font-size: 20px;
      margin: 0px;
      text-align: center;
      margin-bottom: 10px;
    }

    .report-support-types {
      display: flex;
      justify-content: center;

      .item-type {
        margin: 5px;
        font-size: 20px;
        border: 1px solid #CCC;
        border-radius: 3px;
        width: 40px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        &:hover {
          border-color: #409EFF;
          color: #409EFF;
        }

        &.active {
          border-color: #409EFF;
          background: #409EFF;
          color: #FFF;
        }

        &.disabled {
          color: #CCC;
          border-color: #DDD;
          background: #DDD;
        }
      }
    }

    .v-chart-area {
      width: 460px;
      height: 300px;
      margin: 10px auto;
    }

    .report-view {
      flex: 1;
      overflow-y: auto;
    }
  }
}

.report-lowcode-tag {
  font-size: 13px;
  display: flex;
  cursor: pointer;
  color: #409EFF;

  i {
    margin-right: 5px;
  }
}
</style>
